<?php
namespace Admin\Controller;
use Think\Controller;
use Think\Exception;
class UserController extends BaseController {
	private $model;
	function __construct() {
		parent::__construct();
		$this->model = D('Admin');
	}
	/**
	 * 用户列表
	 * @nav L('user_list')
	 */
    public function index() {
    	if(I('get.data','')){
    		$role_user_module = D('Roleuser');
    		if(I('get.role_id','')){
    			$userwhere = array('role_id'=>I('get.role_id',''));
    			$roleuser = $role_user_module->SelectRole($userwhere,'user_id');
    			foreach($roleuser as $key=>$val){
    				$userrole[] = $val['user_id'];
    			}
    			$userwhere = 'userid in ('.implode(',', $userrole).')';
    			$rel = $this->model->SelectUser($userwhere);
    		}else{
    			$rel = $this->model->SelectUser();
    		}
    		#获取用户角色
    		$adminer = C('ADMINISTRATOR_USERID');
    		foreach($rel as $key=>$val){
    			$where = array('user_id'=>$val['userid']);
    			$role = $role_user_module->RoleLeftselct($where);
    			if(in_array($val['userid'],$adminer)){	
    				$rel_role['name'] .= '超级管理员';
    				$rel_role['en_name'] .= 'Administrator';
    			}else if($role){
    				foreach($role as $k=>$v){
    					$str = $role[$k+1]?',':'';
    					$rel_role['name'] .= $v['name'].$str;
    					$rel_role['en_name'] .= $v['en_name'].$str;
    				}
    			}
    			$rel[$key]['role'] = $rel_role?$rel_role:false;
    			$rel_role = array();
    		}
    		$this->ajaxReturn( ajax_return_join(200, $rel, 'cms_success'));
    	}else{
    		$this->display();
    	}
    	
    }

    /**
     * 添加用户
     *@nav  L('user_add')
    */     
    public function doAdduser() {
    
    	$post = I('post.');
        if($post['dosubmit']){
        	foreach($post as $key=>$val){
        		if(!$val){
        			$this->ajaxReturn( ajax_return_join(201, '', 'user_empty_prompt'));exit;
        		}
        	}
        	$pwd_key = pwd_key();
//         	$pwd = substr(md5($pwd_key),15);
        	$pwd = I("post.user_pwd",'');
        	if( !$pwd ){
        		$this->ajaxReturn( ajax_return_join(203, '', 'user_pwd_error'));exit;
        	}
//         	if(!I('post.user_email','',FILTER_VALIDATE_EMAIL)){
//         		$this->ajaxReturn( ajax_return_join(203, '', 'user_email_error'));exit;
//         	}
//         	if(!I('post.user_leader_email','',FILTER_VALIDATE_EMAIL)){
//         		$this->ajaxReturn( ajax_return_join(203, '', 'user_email_error'));exit;
//         	}
        	if(!preg_match("/^(13[0-9]|15[0|3|2|6|7|8|9]|170|18[5|6|7|8|9])\d{8}$/",$post['user_phone'])){
        		$this->ajaxReturn( ajax_return_join(204, '', 'user_phone_error'));exit;
        	}
        	$yemail = $rel = $this->model->FindUser("email='".$post['user_email']."'");
        	if($yemail){
        		$this->ajaxReturn( ajax_return_join(205, '', 'user_email_exist'));exit;
        	}
        	
        	$post['user_pwd'] = md5(md5($pwd).$pwd_key);
        	$data = array(
        		'email' => $post['user_email'],
        		'real_name' => $post['user_name'],
        		'password' => $post['user_pwd'],
        		'pwd_key' => $pwd_key,
        		'phone_num' => $post['user_phone'],
        		'leader' => $post['user_leader'],
        		'leader_email' => $post['user_leader_email'],
        		'department' => $post['user_department'],
        		'lang' => $post['user_lang'],
        		'status' =>1
        	);
        	$rel = $this->model->AddUser($data);
        	if($rel){
        		#角色认定
        		$role = $post['role'];
        		if($role){
        			$role_user_module = D('Roleuser');
        			foreach($role as $k=>$v){
        				$roledata[] = array('user_id'=>$rel,'role_id'=>$v);
        			}
        			$role_user_module->AddRoleall($roledata);
        		}
        		
//         		$msg = new \Com\Cmcm\Mail();
//         		$users   = array
//         		(
//         				array('email'=>$post['user_email'],'username'=>$post['user_name'])
//         		);
//         		if($post['user_lang']=='zh-cn'){
//         			$body = "
// 	        			<p>尊敬的“".$post['user_name']."”您好：</p>
//                         <p>&nbsp;&nbsp;&nbsp;&nbsp;您的邮箱:".$post['user_email']."</p>
// 	        			<p>&nbsp;&nbsp;&nbsp;&nbsp;您的密码:".$pwd."</p>
// 	        			<p>&nbsp;&nbsp;&nbsp;&nbsp;<a href='http://cmbi.cms.cmcm.com' target='__blank'>点击立即体验</a></p>
// 	        			<p>&nbsp;&nbsp;&nbsp;&nbsp;备注：请登录系统修改您的密码</p><br/>	";
//         			$title ='移动分发系统新用户通知';
//         		}else{
//         			$body = "
// 	        			<p>Dear ".$post['user_name']."：</p>
//                         <p>&nbsp;&nbsp;&nbsp;&nbsp;Your email:".$post['user_email']."</p>
// 	        			<p>&nbsp;&nbsp;&nbsp;&nbsp;Your passpowd:".$pwd."</p>
// 	        			<p>&nbsp;&nbsp;&nbsp;&nbsp;<a href='http://cmbi.cms.cmcm.com' target='__blank'>Click on the immediate experience</a></p>
// 	        			<p>&nbsp;&nbsp;&nbsp;&nbsp;Note: please login system to modify your password</p><br/>	";
//         			$title ='CM Manager new user notification';
//         		}
        		
        		//$rs = $msg->sendMail($users,$body,$title);
        		$this->ajaxReturn( ajax_return_join(200, '', 'cms_success'));exit;
        	}else{
        		$this->ajaxReturn( ajax_return_join(500, '', 'cms_other_error'));exit;
        	}
        }else{
        	#获取角色组
        	$role_model = D('Role');
        	$rel = $role_model->SelectRole();
        	$this->assign('rolerel',$rel);
        	$this->display();
        }
    }
    /**
     * 修改用户信息
     * @nav L('user_edit')
     */
	public function userEdit(){
		if(I('get.id')){
			$userinfo = $this->model->FindUser("userid='".I('get.id')."'");
			if(I('post.dosubmit')){
				$post = I('post.');
				if(!$post['user_pwd']){
					unset($post['user_pwd']);
				}else{
					if(strlen($post['user_pwd'])>20 || strlen($post['user_pwd'])<6){
						$this->ajaxReturn( ajax_return_join(202, '', 'user_pwd_error'));exit;
					}
					$pwd_key = pwd_key();
					$post['user_pwd'] = md5(md5($post['user_pwd']).$pwd_key);
				}
				foreach($post as $key=>$val){
					if(!$val && $key!='user_status'){
						$this->ajaxReturn( ajax_return_join(201, '', 'user_empty_prompt'));exit;
					}
				}
// 				if(!I('post.user_email','',FILTER_VALIDATE_EMAIL)){
// 					$this->ajaxReturn( ajax_return_join(203, '', 'user_email_error'));exit;
// 				}
// 				if(!I('post.user_leader_email','',FILTER_VALIDATE_EMAIL)){
// 					$this->ajaxReturn( ajax_return_join(203, '', 'user_email_error'));exit;
// 				}
				if(!preg_match("/^(13[0-9]|15[0|3|2|6|7|8|9]|170|18[5|6|7|8|9])\d{8}$/",$post['user_phone'])){
					$this->ajaxReturn( ajax_return_join(204, '', 'user_phone_error'));exit;
				}
				$data = array(
						'email' => $post['user_email'],
						'real_name' => $post['user_name'],
						'phone_num' => $post['user_phone'],
						'leader' => $post['user_leader'],
						'leader_email' => $post['user_leader_email'],
						'department' => $post['user_department'],
						'lang' => $post['user_lang'],
						'status' =>$post['user_status']
				);
				if($post['user_pwd']){
					$data['password'] = $post['user_pwd'];
					$data['pwd_key'] = $pwd_key;
				}
	    		$where = 'userid='.$userinfo['userid'];
	    		$rel = $this->model->UpdataInfo($where,$data);
	    		#清空已有角色组
	    		$role_user_module = D('Roleuser');
	    		$where = array('user_id'=>$userinfo['userid']);
	    		$drel = $role_user_module->RoleuserDel($where);
	    		#插入新角色
				$role = $post['role'];
        		if($role){
        			foreach($role as $k=>$v){
        				$roledata[] = array('user_id'=>$userinfo['userid'],'role_id'=>$v);
        			}
        			$rel_role = $role_user_module->AddRoleall($roledata);
        		}
	    		
				if($rel || $rel_role){
					$this->ajaxReturn( ajax_return_join(200, '', 'cms_success'));exit;
				}else{
					$this->ajaxReturn( ajax_return_join(302, '', 'user_edit_faild'));exit;
				}
			}else{
				$role_model = D('Role');
				$rel = $role_model->SelectRole();
				$this->assign('rolerel',$rel);
				$this->assign('rel',$userinfo);
				
				#查询已有角色
				$role_user_module = D('Roleuser');
				$where = array('user_id'=>$userinfo['userid']);
				$Rolepermissions = $role_user_module->SelectRole($where,'role_id');
				foreach($Rolepermissions as $key=>$val){
					$userrole[] = $val['role_id'];
				}
				$this->assign('userrole',$userrole);
				
				$this->display();
			}
		}else{
			redirect(U('user/index'));
		}
	}

    /**
     * [profile 个人信息]
     * @privilege public
     * @return [type] [description]
     */
    public function profile()
    {
        if( IS_POST )
        {
            try{
                $ret['status']  = 200;
                $ret['content'] = '';
                $ret['msg']     = '个人信息修改成功！';

                $data = array();
                $post = I('post.');
                //第一次登陆，修改基本信息密码必须填写
                if(session('user_first_login') && empty($post['password']) )
                {
                    E("first login ,password must not empty",401);
                }
                if( $post['password'] ){
                    if(strlen($post['password'])>20 || strlen($post['password'])<6){
                        E(L('user_pwd_error') , 410);
                    }
                    $pwd_key = pwd_key();
                    $data['password'] = md5(md5($post['password']).$pwd_key);
                    $data['pwd_key'] = $pwd_key;
                }

                $data['real_name'] = htmlspecialchars($post['real_name']);
                if( empty($data['real_name']) )
                {
                    E('user name is not empty！',410);
                }

                $data['phone_num'] = htmlspecialchars($post['phone_num']);
                if(!preg_match("/^(13[0-9]|15[0|3|2|6|7|8|9]|170|18[5|6|7|8|9])\d{8}$/",$data['phone_num']))
                {
                    E( L('user_phone_error') , 401 );
                }

                $data['leader'] = htmlspecialchars($post['leader']);
                if( empty($data['leader']) )
                {
                    E('leader name is not empty！',410);
                }

                $data['leader_email'] = htmlspecialchars($post['leader_email']);
                if( empty($data['leader_email']) )
                {
                    E('leader email is not empty！',410);
                }

                $data['department'] = htmlspecialchars($post['department']);
                if( empty($data['department']) )
                {
                    E('department is not empty！',410);
                }
                $data['lang'] = htmlspecialchars($post['lang']);

                $where = array();
                $where['userid'] = session('userid');
                $this->model->where( $where )->save( $data );

                session('user_first_login',null);
            }catch(\Exception $e){
                $ret['msg'] = $e->getMessage();
                $ret['status'] = $e->getCode();
            }
            $this->ajaxReturn($ret);
        }

        $db_prefix = C('DB_PREFIX');
        
        $where = array();
        $uid = $where['userid'] = session('userid');
        $userInfo = $this->model->where( $where )->find();
        $job = '';
        if( in_array($uid, C('ADMINISTRATOR_USERID') ) )
        {
            $job = "Super admin";
        }else{
            $sql = 'SELECT * from '.$db_prefix.'role WHERE role_id in(
                        SELECT role_id FROM '.$db_prefix.'role_user WHERE user_id='.$uid.'
                    )';
            $m = M();
            $jobRs = $m->query($sql);
            if( $jobRs )
            {
                foreach ($jobRs as $key => $value) {
                    $job_arr[]=$value['name'];
                }
                $job = implode(',', $job_arr);
            }
        }
        $is_first_login = session('user_first_login')?1:0;
        $this->assign('job',$job);
        $this->assign('date',date("F d,Y"));
        $this->assign('user',$userInfo);
        $this->assign('is_first_login',$is_first_login);
        $this->display();
    }
}


